<script setup lang="ts" name="VaccinationHistory">
import {computed, onBeforeUnmount, onDeactivated, onMounted, reactive, ref} from 'vue'
import {HeaderData, Operation as Opr} from '@/components/dTable/dTable'
import dTablePromote from '@/components/dTable/dTable.vue'
import operation from '@/components//dTable/components/operation.vue'
import dIcon from '@/components/dIcon.vue'
import VaccineLibrary from './vaccineLibrary/index.vue'
import zhCN from 'ant-design-vue/es/locale/zh_CN'
import {ColorRed, ColorTheme, IconConfig} from '@/api/config'
import useUser from '@/store/user'
import {ElMessage, FormRules} from 'element-plus/es'
import {getVaccinationHistory, getVaccineStoreByName, rejectVaccinationHistory, saveVaccinationHistory, VaccinationHistory} from '@/api/medicalExaminerDesk/beginPhysicalExamination/vaccinationHistory'
import dayjs, {Dayjs} from 'dayjs'
import {NotLeadingAndTrailingSpaces} from '@/util/common'
import {fieldRequired} from '@/api/medicalExaminerDesk/beginPhysicalExamination'
import {showMessageBox} from '@/util/element'
const user = useUser.setup().store

const props = defineProps({
  // 体检登记表id
  checkupRegisterId: {
    type: String,
    required: true,
    default: ''
  },
  // 禁止编辑
  disEdit: {
    type: Boolean,
    required: true,
    default: false
  },
  // 性别
  gender: {
    type: String,
    required: false,
    default: ''
  }
})

// 保存和拒检的加载
const showSaveLoading = ref<boolean>(false)

// 表格加载
const showLoading = ref(false)

//体检医生id
const dutyDoctorId = ref<string | undefined>()
// 体检医生姓名
const dutyDoctorName = ref<string | undefined>()

// 控制是否现在校验提示
const showErrorTips = ref<boolean>(true)

//表格头数据
const tableHeaderDatas = ref<Array<HeaderData>>([
  {prop: 'inocName', label: '疫苗名称', columnType: 'slot', align: 'left', 'min-width': '300'},
  {prop: 'inocDate', label: '接种日期', columnType: 'slot', align: 'left', width: '233'},
  {prop: 'unitsName', label: '接种机构', columnType: 'slot', align: 'left', 'min-width': '320'},
  {prop: 'operation', label: '操作', columnType: 'slot', width: '83'}
])

// 禁止编辑的时候去掉操作列
props.disEdit && (tableHeaderDatas.value = tableHeaderDatas.value.slice(0, -1))

const tableHeaderBtnIcon: IconConfig = {icon: 'common-vaccine-library', type: 'custom', size: 16}

// 操作按钮数据
const operationDataDelete: Array<Opr> = [
  {
    code: 'delete',
    label: '删除',
    iconConfig: {icon: 'common-delete', type: 'custom', color: ColorRed, size: 20}
  }
]

// 操作按钮数据
const operationDataAdd: Array<Opr> = [
  {
    code: 'add',
    label: '添加',
    iconConfig: {icon: 'common-swap-add', type: 'custom', color: ColorTheme, size: 20}
  }
]

// 错提示图标
const errorIcon: IconConfig = {
  icon: 'CircleCloseFilled',
  type: 'el',
  size: 16,
  color: ColorRed
}

const showDialog = ref(false)

// 空数据表格
const emptyTableData: VaccinationHistory = {inocName: '', inocDate: '', unitsName: ''}

// 非免疫规划预防接种史列表
const formData = reactive<{vaccinationHistoryTable: Array<VaccinationHistory>}>({
  vaccinationHistoryTable: [
    {...emptyTableData, ...{operation: operationDataAdd}},
    {...emptyTableData, ...{operation: operationDataAdd}}
  ]
})

// 表单实例
const formRef = ref()

// 体检大类的体检医生姓名
const dutyDoctorName8 = computed(() => {
  return dutyDoctorName.value || (user.userInfor?.jobName === '医生' ? user.userInfor?.userName : '')
})

// 体检状态
const checkupStatus8 = computed(() => {
  return formData.vaccinationHistoryTable[0]?.checkupStatus
})

const rules = computed<FormRules>(() => {
  return {
    inocName: [
      {
        message: '最多100个字符!',
        trigger: ['change', 'blur'],
        max: 100
      },
      {
        message: '首尾不能为空格!',
        pattern: NotLeadingAndTrailingSpaces,
        trigger: ['change', 'blur']
      },
      {required: fieldRequired('inocName'), message: '请输入疫苗名称!', trigger: []}
    ],
    inocDate: [{required: fieldRequired('inocDate'), message: '请选择接种日期!', trigger: []}],
    unitsName: [
      {
        message: '最多100个字符!',
        trigger: ['change', 'blur'],
        max: 100
      },
      {
        message: '首尾不能为空格!',
        pattern: NotLeadingAndTrailingSpaces,
        trigger: ['change', 'blur']
      },
      {required: fieldRequired('fmyUnitsName'), message: '请输入接种机构!', trigger: []}
    ]
  }
})

/**
 * @description: 改变当前行日期触发校验
 * @param {*} index
 * @return {*}
 */
const onChangeDate = (index: number) => {
  formRef.value.validateField(`vaccinationHistoryTable.${index}.inocDate`)
}

/**
 * @description: 添加展示按钮
 * @param {*} dataList
 * @return {*}
 */
const showButton = (dataList: Array<VaccinationHistory>) => {
  formRef.value && formRef.value.clearValidate() // 清空校验
  const returnList: Array<VaccinationHistory> = []
  dataList.map((item, index) => {
    returnList.push({...item, operation: index === dataList.length - 1 ? [...operationDataAdd, ...operationDataDelete] : operationDataDelete})
  })
  return returnList
}

/**
 * @description: 删除非免疫规划预防接种史
 * @param {*} index
 * @return {*}
 */
const onRemoveVaccinationHistory = (index: number) => {
  formData.vaccinationHistoryTable.splice(index, 1)
  formData.vaccinationHistoryTable = showButton(formData.vaccinationHistoryTable)
  if (formData.vaccinationHistoryTable.length === 0) {
    formData.vaccinationHistoryTable = [{...emptyTableData, ...{operation: operationDataAdd}}]
  }
}

/**
 * @description: 添加非免疫规划预防接种史
 * @return {*}
 */
const onAddVaccinationHistory = () => {
  formData.vaccinationHistoryTable.push(emptyTableData)
  formData.vaccinationHistoryTable = showButton(formData.vaccinationHistoryTable)
}

/**
 * @description: 非免疫规划预防接种史列表操作栏点击
 * @param {*} code
 * @param {*} row
 * @return {*}
 */
const onVaccinationHistoryTableOper = (code: string, row: VaccinationHistory) => {
  if (code === 'delete') {
    onRemoveVaccinationHistory(formData.vaccinationHistoryTable.indexOf(row))
  } else if (code === 'add') {
    onAddVaccinationHistory()
  }
}

/**
 * @description: 禁用日期
 * @param {*} current
 * @return {*}
 */
const disabledDate = (current: Dayjs) => {
  return current && current > dayjs().endOf('day')
}

/**
 * @description: 获取体检信息
 * @return {*}
 */
const getInitData = () => {
  showLoading.value = true
  getVaccinationHistory(props.checkupRegisterId)
    .then((res) => {
      const {data} = res.data || []
      data?.length && (formData.vaccinationHistoryTable = data)
      if (formData.vaccinationHistoryTable.length === 0) {
        formData.vaccinationHistoryTable = [{...emptyTableData, ...{operation: operationDataAdd}}]
      }
      // 获取当前行的体检医生
      formData.vaccinationHistoryTable[0]?.dutyDoctorId && (dutyDoctorId.value = formData.vaccinationHistoryTable[0]?.dutyDoctorId)
      formData.vaccinationHistoryTable[0]?.dutyDoctorName && (dutyDoctorName.value = formData.vaccinationHistoryTable[0]?.dutyDoctorName)
      formData.vaccinationHistoryTable = showButton(formData.vaccinationHistoryTable)
    })
    .finally(() => {
      showLoading.value = false
      showSaveLoading.value = false
      formRef.value?.clearValidate()
    })
}

/**
 * @description: 保存
 * @return {*}
 */
const onSave8 = () => {
  showErrorTips.value = true
  formRef.value &&
    formRef.value.validate((valid: boolean, fields) => {
      if (valid) {
        showSaveLoading.value = true
        const params = formData.vaccinationHistoryTable.map((item) => {
          return {
            id: item.id,
            checkupStatus: 2, //2已检
            checkupRegisterId: props.checkupRegisterId,
            dutyDoctorId: dutyDoctorId.value || user.userInfor?.id,
            dutyDoctorName: dutyDoctorId.value !== user.userInfor?.id ? dutyDoctorName.value || user.userInfor?.userName : user.userInfor?.userName,
            inocName: item.inocName, // 疫苗名称
            inocDate: item.inocDate, // 接种时间
            unitsName: item.unitsName // 接种机构名称
          }
        })
        saveVaccinationHistory(params)
          .then(() => {
            getInitData()
            ElMessage.success('保存成功!')
          })
          .catch((err) => {
            showSaveLoading.value = false
            console.warn(err)
          })
      } else {
        console.warn(fields)
      }
    })
}

/**
 * @description: 拒检
 * @return {*}
 */
const onRejectInspection8 = () => {
  showMessageBox('是否对该体检大类进行拒检操作？', {title: '拒检确认', mesageType: 'base'})
    .then(() => {
      showSaveLoading.value = true
      const params = formData.vaccinationHistoryTable.map((item) => {
        return {
          id: item.id,
          checkupStatus: 1, // 1拒检
          checkupRegisterId: props.checkupRegisterId,
          dutyDoctorId: dutyDoctorId.value || user.userInfor?.id,
          dutyDoctorName: dutyDoctorId.value !== user.userInfor?.id ? dutyDoctorName.value || user.userInfor?.userName : user.userInfor?.userName,
          inocName: null, // 疫苗名称
          inocDate: null, // 接种时间
          unitsName: null // 接种机构名称
        }
      })
      rejectVaccinationHistory(params)
        .then(() => {
          ElMessage.success('拒检成功!')
          getInitData()
        })
        .catch((error) => {
          showSaveLoading.value = false
          console.warn(error)
        })
    })
    .catch((error) => {
      console.warn(error)
    })
}

/**
 * @description: 搜索疫苗名称
 * @param {*} inocName 疫苗名称
 * @param {*} cb
 * @return {*}
 */
const searchInocName = (inocName: string, cb) => {
  // 长度校验，和首尾空格校验不通过不请求数据
  if (inocName.length > 100 || !NotLeadingAndTrailingSpaces.test(inocName)) {
    cb([])
    return
  }
  getVaccineStoreByName({inocName}).then((res) => {
    const {data} = res.data || []
    cb(data)
  })
}

/**
 * @description: 选择疫苗名称
 * @param {*} item 下拉值
 * @param {*} index // 表格的行下标
 * @return {*}
 */
const handleSelect = (item, index: number) => {
  formData.vaccinationHistoryTable[index].inocName = item.inocName //疫苗名称
  formData.vaccinationHistoryTable[index].unitsName = item.unitsName // 接种机构
}

onMounted(() => {
  getInitData()
})

onBeforeUnmount(() => {
  showErrorTips.value = false
})

onDeactivated(() => {
  showErrorTips.value = false
})
</script>

<template>
  <div class="d-check-up-desk-content">
    <el-button v-blur type="primary" class="table-header-btn" @click="showDialog = true">
      <d-icon class="el-icon el-icon--left" :icon-config="tableHeaderBtnIcon" />
      疫苗库维护
    </el-button>
    <el-form ref="formRef" :rules="rules" :model="formData" :disabled="disEdit">
      <d-table-promote class="d-common-flex-full vaccination-history-table" :table-data="formData.vaccinationHistoryTable" :table-header-data="tableHeaderDatas" :show-loading="showLoading">
        <template #inocName="scope">
          <el-form-item :prop="`vaccinationHistoryTable.${scope.index}.inocName`" :rules="rules.inocName" :inline-message="true" class="d-common-width-full">
            <el-autocomplete
              v-model="scope.row.inocName"
              placeholder="请输入疫苗名称"
              :fetch-suggestions="searchInocName"
              :debounce="600"
              :highlight-first-item="true"
              :trigger-on-focus="false"
              :fit-input-width="true"
              :clearable="true"
              @select="
                (item) => {
                  handleSelect(item, scope.index)
                }
              "
            >
              <template #default="{item}">
                <div class="value">
                  疫苗名称：{{ item.inocName }}(疫苗代码:{{ item.inocCode }} )
                </div>
              </template>
            </el-autocomplete>
            <template #error="{error}">
              <div>
                <el-popover
                  :visible="showErrorTips"
                  :width="200"
                  :hide-after="0"
                  :persistent="false"
                  transition="none"
                  placement="right"
                  popper-class="error-tip"
                >
                  <d-icon :icon-config="errorIcon" />
                  {{ error }}
                  <template #reference>
                    <span />
                  </template>
                </el-popover>
              </div>
            </template>
          </el-form-item>
        </template>
        <template #inocDate="scope">
          <el-form-item :prop="`vaccinationHistoryTable.${scope.index}.inocDate`" :rules="rules.inocDate" :inline-message="true" class="d-common-width-full">
            <a-config-provider :locale="zhCN">
              <A-date-picker
                v-model:value="scope.row.inocDate"
                format="YYYY-MM-DD"
                :disabled-date="disabledDate"
                :disabled="disEdit"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择接种日期"
                @change="onChangeDate(scope.index)"
              />
            </a-config-provider>
            <template #error="{error}">
              <div>
                <el-popover
                  :visible="showErrorTips"
                  :width="200"
                  :hide-after="0"
                  :persistent="false"
                  transition="none"
                  placement="right"
                  popper-class="error-tip"
                >
                  <d-icon :icon-config="errorIcon" />
                  {{ error }}
                  <template #reference>
                    <span />
                  </template>
                </el-popover>
              </div>
            </template>
          </el-form-item>
        </template>
        <template #unitsName="scope">
          <el-form-item :prop="`vaccinationHistoryTable.${scope.index}.unitsName`" :rules="rules.unitsName" :inline-message="true">
            <el-input v-model="scope.row.unitsName" placeholder="请输入接种机构" clearable class="d-common-flex-full" />
            <template #error="{error}">
              <div>
                <el-popover
                  :visible="showErrorTips"
                  :width="200"
                  :hide-after="0"
                  :persistent="false"
                  transition="none"
                  placement="top"
                  popper-class="error-tip"
                >
                  <d-icon :icon-config="errorIcon" />
                  {{ error }}
                  <template #reference>
                    <span />
                  </template>
                </el-popover>
              </div>
            </template>
          </el-form-item>
        </template>
        <template #operation="scope">
          <operation :row="scope.row" :col="scope.item" @opertion-click="onVaccinationHistoryTableOper" />
        </template>
      </d-table-promote>
    </el-form>
  </div>
  <div class="d-check-up-desk-footer d-common-flex-center d-common-width-full">
    <span class="doctor">体检医生：</span>
    <el-input v-model="dutyDoctorName8" disabled />
    <el-button type="primary" :loading="showSaveLoading" :disabled="disEdit" @click="onSave8()">
      保存
    </el-button>
    <el-button type="danger" :loading="showSaveLoading" :disabled="(checkupStatus8 && checkupStatus8 === 1) || disEdit" plain @click="onRejectInspection8()">
      拒检
    </el-button>
  </div>
  <vaccine-library v-if="showDialog" :show-dialog="showDialog" @close="showDialog = false" />
</template>

<style scoped lang="less">
.table-header-btn {
  margin-bottom: 20px;
}
.vaccination-history-table {
  min-height: 65vh;
}
:deep(.el-autocomplete) {
  width: 100%;
}
</style>
